package com.wenzil.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.wenzil.common.utils.HttpUtils;
import com.wenzil.common.utils.R;
import com.wenzil.gulimall.auth.feign.MemberFeignService;
import com.wenzil.common.vo.MemberRespVo;
import com.wenzil.gulimall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理社交登录请求
 */
@Slf4j
@Controller
public class OAuth2Controller {
    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 社交登录成功回调
     * @param code
     * @param session
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session, HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest) throws Exception {
//        HttpSession session1 = httpServletRequest.getSession();
//        session1.setAttribute("", "");

        Map<String, String> map = new HashMap<>();
        map.put("client_id","4262374430");
        map.put("client_secret","e3a0d34dc84b061eb0f4219c2b044d2c");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code",code);

        //1、根据用户授权返回的code换取access_token
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), map, new HashMap<>());
        if (response.getStatusLine().getStatusCode() == 200) {
            // 获取到accessToken
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            // 知道当前是哪个社交用户
            R r = memberFeignService.oauthlogin(socialUser);
            if (r.getCode() == 0) {
                MemberRespVo data = (MemberRespVo) r.getData("data", new TypeReference<MemberRespVo>() {});
                log.info("登录成功：用户信息：{}", data.toString());
                session.setAttribute("loginUser", data);
                // 2、登录成功就跳转到首页
                return "redirect:http://gulimall.com";
            } else {
                return "redirect:http://auth.gulimall.com/login.html";
            }

        } else {
            return "redirect:http://auth.gulimall.com/login.html";
        }

    }

}
